import { Method, AxiosRequestConfig, CancelToken } from 'axios';
import service from '../utils/request';
import { set } from 'lodash';
import axios from 'axios';
import { message } from 'antd';

export const customApi =
  <T = any, U = any>(url: string, method: Method = 'post', _header: any = {}) =>
  async (data?: T, header1?: any, sourceToken?: CancelToken): Promise<U> => {
    const requestOption: AxiosRequestConfig = {
      url: url,
      headers: {
        Authorization: localStorage.getItem('token'),
        ..._header,
        ...header1,
      },
      cancelToken: sourceToken,
    };
    url.includes('login') && delete requestOption.headers?.Authorization;
    set(requestOption, 'method', method);
    set(
      requestOption,
      method === 'get' || method === 'GET' ? 'params' : 'data',
      data,
    );

    try {
      const response = await service.request<T, U>(requestOption);
      return response;
    } catch (err) {
      throw err;
    }
  };

export const downloadApi =
  <T = any>(url: string, method: Method = 'post', _header: any = {}) =>
  async (fileName: string, data?: T, header1?: any) => {
    const requestOption: AxiosRequestConfig = {
      url: window.config.SERVER_HOST + url,
      headers: {
        Authorization: localStorage.getItem('token'),
        ..._header,
        ...header1,
      },
      responseType: 'blob',
    };

    set(requestOption, 'method', method);
    set(
      requestOption,
      method === 'get' || method === 'GET' ? 'params' : 'data',
      data,
    );

    return axios(requestOption)
      .then((res) => {
        let a = document.createElement('a');
        const url = window.URL.createObjectURL(res.data);
        a.href = url;
        a.style.display = 'none';
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
        return Promise.resolve();
      })
      .catch((err) => {
        message.error('下载失败！');
        throw err;
      });
  };
